

import { _decorator, Component, game, Node } from 'cc';
import EventManager from '../../Runtime/EventManager';
import { CONTROLLER_ENUM, EVENT_ENUM, SHAKE_TYPE_ENUM } from '../../Enum';
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = ControllerManager
 * DateTime = Tue Jun 27 2023 10:16:01 GMT+0800 (中国标准时间)
 * Author = zshzshzsh15
 * FileBasename = ControllerManager.ts
 * FileBasenameNoExtension = ControllerManager
 * URL = db://assets/Script/UI/ControllerManager.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */

@ccclass('ShakeManage')
export class ShakeManage extends Component {
    private isShaking = false

    private oldTime: number = 0
    private type: SHAKE_TYPE_ENUM

    private oldPos: { x: number, y: number } = { x: 0, y: 0 }
    onLoad() {
        EventManager.Instance.on(EVENT_ENUM.SCREEN_SHAKE, this.onShake, this)
    }
    onDisable() {

        EventManager.Instance.off(EVENT_ENUM.SCREEN_SHAKE, this.onShake)
    }


    onShake(type: SHAKE_TYPE_ENUM) {

        if (this.isShaking) {
            return
        }
        this.type = type
        this.oldTime = game.totalTime
        this.isShaking = true
        this.oldPos.x = this.node.position.x
        this.oldPos.y = this.node.position.y

    }


    update(dt: number): void {

        if (this.isShaking) {
            const duration = 200
            const amount = 16
            const frequency = 12
            const curSecond = (game.totalTime - this.oldTime) / 1000    //秒
            const totalSecond = duration / 1000

            const offset = amount * Math.sin(frequency * Math.PI * curSecond)


            //偏移
            // this.node.setPosition(this.oldPos.x,this.oldPos.y+offset)

            if (this.type === SHAKE_TYPE_ENUM.TOP) {

                this.node.setPosition(this.oldPos.x, this.oldPos.y - offset)
            } else if (this.type === SHAKE_TYPE_ENUM.BOTTOM) {

                this.node.setPosition(this.oldPos.x, this.oldPos.y + offset)
            } else if (this.type === SHAKE_TYPE_ENUM.RIGHT) {

                this.node.setPosition(this.oldPos.x + offset, this.oldPos.y)
            } else if (this.type === SHAKE_TYPE_ENUM.LEFT) {

                this.node.setPosition(this.oldPos.x - offset, this.oldPos.y)
            }

            if (curSecond > totalSecond) {
                this.isShaking = false
                this.node.setPosition(this.oldPos.x, this.oldPos.y)
            }


        }

    }



    stop() {
        this.isShaking = false
    }
}


